package com.fc.persistence.core;

import java.util.List;

import com.fc.persistence.dao.MongoEntityTemplate;
import com.google.code.morphia.query.Query;

public class MongoClientFacade {
	private static IMongoClientImpl clientImpl;

	public static void initMongoClient() {
		if (clientImpl == null) {
			clientImpl = new IMongoClientImpl();
		}
	}
	
	public static void close(){
		clientImpl.close();
	}

	public static void saveProxy(MongoEntityTemplate entity) {
		clientImpl.getDatastore().save(entity);
	}

	public List<? extends MongoEntityTemplate> findByContains(Class<? extends MongoEntityTemplate> clazz, String field,
			String contains) {
		return clientImpl.getDatastore().find(clazz).field(field).contains(contains).asList();
	}
	
	public List<? extends MongoEntityTemplate> findByContainsIgnoreCase(Class<? extends MongoEntityTemplate> clazz, String field,
			String contains) {
		return clientImpl.getDatastore().find(clazz).field(field).containsIgnoreCase(contains).asList();
	}
	
	public List<? extends MongoEntityTemplate> findByEndsWithIgnoreCase(Class<? extends MongoEntityTemplate> clazz, String field,
			String ends) {
		return clientImpl.getDatastore().find(clazz).field(field).endsWithIgnoreCase(ends).asList();
	}
	
	public List<? extends MongoEntityTemplate> findByField(Class<? extends MongoEntityTemplate> clazz, String field,
			boolean exists) {
		if(exists){
			return clientImpl.getDatastore().find(clazz).field(field).exists().asList();
		}
		return clientImpl.getDatastore().find(clazz).field(field).doesNotExist().asList();
	}
	
	
	/**
	 * 通过过滤条件查询
	 * @param clazz
	 * 			要查找的类
	 * @param offset
	 * 			偏移量
	 * @param size
	 * 			数量
	 * @param filters
	 * 			格式为{condition,value,condition,value...}
	 * @return
	 */
	public List<? extends MongoEntityTemplate> queryByFilter(Class<? extends MongoEntityTemplate> clazz, int offset,int size,String... filters) {
		if(filters.length % 2 != 0){
			return null;
		}
		Query<? extends MongoEntityTemplate> temp = clientImpl.getDatastore().createQuery(clazz);
		for(int i=0;i< (filters.length %2);i+=2){
			temp = temp.filter(filters[i], filters[i+1]);
		}
		return temp.offset(offset).limit(size).asList();
	}
	
	public void save(MongoEntityTemplate entity){
		clientImpl.getDatastore().save(entity);
	}
}
